import React, { useState, useRef } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect, Link } from 'umi'
import { querySignContractList,saveContractInfo,deleteContract,finishContract} from '../service'
import {Tabs,message,notification,DatePicker,Divider,Popconfirm} from 'antd'
import {signRemarkList, isRemoteSocialSecurityList} from "@/utils/constant"
import moment from 'moment'
import StepsForm from '../components/StepsForm';
import ComputerAddForm from '../components/CompleteAddForm';
const  { TabPane } = Tabs;

const TableList = ({currentUser}) => {
  const actionRef = useRef();
  const actionRef2 = useRef();
  const [tabIndex, setTabIndex] = useState("0");
  const [visible, setVisible] = useState(false);
  const [record,setRecord] = useState(null);
  const [loading,setLoading] = useState(false);
  const [completeVisible, setCompleteVisible] = useState(false);
  const { authorities } = currentUser;

  const handleChangTabIndex = (key) => {
    setTabIndex(key);
    if(key === '0'){
      actionRef.current &&  actionRef.current.reload();
    }else{
      actionRef2.current && actionRef2.current.reload();
    }
  };

  const signContract = (record) => {
    setVisible(true);
    setRecord(record);
  };

  const handleCancel = () => {
    setVisible(false);
    setCompleteVisible(false);
    setRecord(null);
  };

  const handleSubmit = (values) => {
    setLoading(true);
    setRecord(null);
    saveContractInfo(values).then((res) => {
      if(res.flag){
        setVisible(false);
        message.success('合同发送成功！');
        actionRef.current.reload();
      }else{
        notification.error({
          message: `请求错误 ${res.status}`,
          description: res.error,
        });
      }
      setLoading(false);
    })
  };

  const handleCompleteSubmit = (values) => {
    setLoading(true);
    finishContract(values).then((res) => {
      if(res.flag){
        handleCancel();
        message.success('合同发送成功！');
        actionRef.current.reload()
      }else{
        notification.error({
          message: `请求错误 ${res.status}`,
          description: res.error,
        });
      }
      setLoading(false);
    })
  };

  const delContract = (id) =>{
    deleteContract(id).then(res => {
      if (res.flag) {
        message.success('合同删除成功！');
        actionRef.current.reload();
      } else {
        message.error(res.error);
      }
    });
  };

  const complete = (record) => {
    setRecord(record);
    setCompleteVisible(true);
  };

  const columns = [
    {
      title: '工号',
      dataIndex: 'code',
      hideInSearch: true
    },
    {
      title: '姓名',
      dataIndex: 'name',
      render: (item, record) => (
        <Link to={`/info/details/${record.oid}`}>{item}</Link>
      ),
    },
    {
      title: '公司',
      dataIndex: 'orgName',
    },
    {
      title: '部门',
      dataIndex: 'unitName'
    },
    {
      title: '岗位',
      dataIndex: 'jobName'
    },
    {
      title: '入职日期',
      dataIndex: 'hiredate',
      render: (text) => {
        return text ? moment(text).format('YYYY-MM-DD') : ''
      },
      renderFormItem: (item, props) => {
        return <DatePicker className='widthStyle' {...props} picker="date"/>;
      },
    },
    {
      title: '是否复职',
      dataIndex: 'isReinstate',
      hideInSearch: true,
      render: (text) => {
        const res = isRemoteSocialSecurityList.find((item) => item.value === parseInt(text));
        return res ? res.label : text
      },
    },
    {
      title: '签署原因',
      dataIndex: 'operateType',
      hideInSearch: true,
      render: (text) => {
        const res = signRemarkList.find((item) => item.value === parseInt(text));
        return res ? res.label : text
      },
    },
  ];

  if(tabIndex === '0'){
    columns.push(
      {
        title: '发送状态',
        dataIndex: 'sendStatus',
        hideInSearch: true,
        render: (text,record) => {
          return (record.esignFlowId) ? "已发送" : "未发送";
        },
      },
      {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align:'center',
      width: '20%',
        render: (item, record) => (
          <>
            <a onClick={() => signContract(record)}>签订合同</a>
            <Divider type="vertical"/>
            {(authorities.indexOf("emp:htlb:delete") > -1) && <>
              <Popconfirm title={`是否确认删除?`} onConfirm={() => delContract(record.id)} okText="是" cancelText="否">
              <a>删除</a>
              </Popconfirm>
              <Divider type="vertical"/>
             </>}
            <a onClick={() => complete(record)}>线下签订</a>
          </>
        ),
    })
  };

  return (
    <PageHeaderWrapper>
      <Tabs animated={false} defaultActiveKey="0" onChange={handleChangTabIndex}>
        <TabPane tab="未签署" key="0">
          <ProTable
            actionRef={actionRef}
            rowKey="id"
            request={(params) => querySignContractList(params,[0])}
            columns={columns}
          />
          <StepsForm
            loading={loading}
            visible={visible}
            statusType={'newSign'}
            record={record}
            onCancel={handleCancel}
            onSubmit={handleSubmit}
          />
          <ComputerAddForm
            loading={loading}
            visible={completeVisible}
            record={record}
            type={'newSign'}
            onCancel={handleCancel}
            onSubmit={handleCompleteSubmit}
          />
        </TabPane>
        <TabPane tab="已签署" key="1">
          <ProTable
            actionRef={actionRef2}
            rowKey="id"
            request={(params) => querySignContractList(params,[1,2])}
            columns={columns}
          />
        </TabPane>
      </Tabs>
    </PageHeaderWrapper>
  )
};

export default connect(({user}) => ({
  currentUser: user.currentUser,
}))(TableList)
